package br.com.naotebuk.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author giovanni
 */
public abstract class NaotebukDao<T> implements INaotebukDao<T> {

    @PersistenceContext
    protected EntityManager em;
    
    private Class<T> tipo = getDomainClass();

    @Override
    public void adiciona(T t) {
        em.persist(t);
    }

    @Override
    public void altera(T t) {
        em.merge(t);
    }

    @Override
    public List<T> lista() {
        return em.createNamedQuery(tipo.getSimpleName()+".listar").getResultList();
    }

    @Override
    public T buscaPorId(Integer id) {
        return em.find(tipo, id);
    }

    @Override
    public void remove(T t) {
        em.remove(t);
    }

    private Class getDomainClass() {
        if (tipo == null) {
            ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();
            tipo = (Class) thisType.getActualTypeArguments()[0];
        }
        return tipo;
    }
}